﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ExtensionHelper.Util
{
    public class FileHelper
    {
        /// <summary>
        /// 读取文件，返回文件内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadFile(string filePath, int offset)
        {
            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    if (offset > fs.Length)
                    {
                        return null;
                    }
                    fs.Seek((long)offset, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(fs))
                    {
                        string content = reader.ReadToEnd();
                        return content;
                    }
                }
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 解密文件(使用Base64)
        /// </summary>
        /// <param name="content">文件内容</param>
        /// <returns></returns>
        public static string DecryptFileStr(string content)
        {
            string fileContent = string.Empty;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(ms))
                    {
                        for (int i = 0; i < content.Length; i = i + 1368)
                        {
                            int num = i + 1368;
                            string tempStr = num > content.Length ? content.Substring(i) : content.Substring(i, 1368);
                            byte[] byteArray = Convert.FromBase64String(tempStr);
                            writer.Write(byteArray);
                        }
                    }
                    fileContent = Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch { fileContent = string.Empty; }
            return fileContent;
        }

        /// <summary>
        /// 解密文件(使用Base64)
        /// </summary>
        /// <param name="content">文件内容</param>
        /// <returns></returns>
        public static byte[] DecryptFileBytes(string content)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(ms))
                    {
                        for (int i = 0; i < content.Length; i = i + 1368)
                        {
                            int num = i + 1368;
                            string tempStr = num > content.Length ? content.Substring(i) : content.Substring(i, 1368);
                            byte[] byteArray = Convert.FromBase64String(tempStr);
                            writer.Write(byteArray);
                        }
                    }
                    return ms.ToArray();
                }
            }
            catch { }
            return null;
        }

        /// <summary>
        /// 加密文件(使用Base64)
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <returns></returns>
        public static bool EncryptFile(string inputFile, string outputFile)
        {
            BinaryReader inReader = null;
            StreamWriter outWriter = null;
            try
            {
                outWriter = File.CreateText(outputFile);
                inReader = new BinaryReader(File.OpenRead(inputFile));
                while (true)
                {
                    var buffer = inReader.ReadBytes(1024);
                    if (buffer.Length > 0)
                    {
                        outWriter.Write(Convert.ToBase64String(buffer));
                        outWriter.Flush();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                if (inReader != null)
                {
                    inReader.Close();
                }
                if (outWriter != null)
                {
                    outWriter.Close();
                    outWriter.Dispose();
                }
            }
            return true;
        }

        /// <summary>
        /// 网络连接测试
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public static bool ConnectionTest(string ip)
        {
            try
            {
                System.Net.NetworkInformation.PingReply pingReply = new System.Net.NetworkInformation.Ping().Send(ip);
                return pingReply.Status == System.Net.NetworkInformation.IPStatus.Success;
            }
            catch { return false; }
        }

        /// <summary>
        /// 获取文件的MD5
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string HashMd5(string path)
        {
            try
            {
                if (!File.Exists(path))
                {
                    return "";
                }
                using (var file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    using (var md5 = new MD5CryptoServiceProvider())
                    {
                        var hashByte = md5.ComputeHash(file);
                        return BitConverter.ToString(hashByte).Replace("-", "").ToLower();
                    }
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 复制文件夹到新文件夹
        /// </summary>
        /// <param name="sourceFolder"></param>
        /// <param name="destFolder"></param>
        /// <returns></returns>
        public static bool CopyFile(string sourceFolder, string destFolder)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (destFolder[destFolder.Length - 1] != Path.DirectorySeparatorChar)
                {
                    destFolder += Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(destFolder))
                {
                    Directory.CreateDirectory(destFolder);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                string[] fileList = Directory.GetFileSystemEntries(sourceFolder);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    if (Directory.Exists(file))
                    {
                        // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                        CopyFile(file, destFolder + Path.GetFileName(file));
                    }
                    else
                    {
                        // 否则直接Copy文件
                        File.Copy(file, destFolder + Path.GetFileName(file), true);
                    }
                }
            }
            catch { return false; }
            return true;
        }
        /// <summary>
        /// 获取文件大小(M)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static long GetFileSize(string filePath)
        {
            if (!File.Exists(filePath))
                return 0;
            return (new FileInfo(filePath).Length) / 1024;
        }
    }
}
